import axios from 'axios'
import store from '@/store'
import { Notice } from 'view-design'

// 创建 axios 实例
const service = axios.create({
  baseURL: process.env.VUE_APP_API_BASE_URL, // api base_url
  timeout: 6000 // 请求超时时间
})

const err = (error) => {
  if (error.response) {
    const data = error.response.data
    const token = store.state.user.token
    if (error.response.status === 403) {
      Notice.error({
        title: '403',
        desc: data.title
      })
    }
    if (error.response.status === 401 && !(data.result && data.result.isLogin)) {
      Notice.error({
        title: '未登录',
        desc: '权限校验失败'
      })
      if (token) {
        store.dispatch('Logout').then(() => {
          setTimeout(() => {
            window.location.reload()
          }, 1500)
        })
      }
    }
  }
  return Promise.reject(error)
}

// request interceptor
service.interceptors.request.use(config => {
  const token = store.state.user.token
  if (token) {
    config.headers['Access-Token'] = token // 让每个请求携带自定义 token 请根据实际情况自行修改
  }
  return config
}, err)

// response interceptor
service.interceptors.response.use((response) => {
  return response.data
}, err)

export default service
